from flask import request, Blueprint
from flask_restful import Api, Resource
from sqlalchemy import or_

from models.init_sqlalchemy import db
from models.models import FriendRequests, User
import uuid
from flask_jwt_extended import jwt_required, get_jwt_identity
from utils.h_result import HResult
from datetime import datetime
from utils.utils import to_beijing_time

bp = Blueprint('friend_requests', __name__, url_prefix='/friend-requests/')

class SendFriendRequest(Resource):
    method_decorators = [jwt_required()]
    
    def post(self):
        data = request.get_json()
        receiver_id = data.get('receiver_id')
        current_user = get_jwt_identity()
        
        if not receiver_id:
            return HResult().get_result('error', '参数错误!')
            
        user = User.query.filter_by(name=current_user).first()
        
        # 检查是否已经发送过请求
        existing_request = FriendRequests.query.filter_by(
            sender_id=user.id,
            receiver_id=receiver_id,
            status='pending'
        ).first()
        
        if existing_request:
            return HResult().get_result('error', '已经发送过好友请求!')
            
        friend_request = FriendRequests(
            id=str(uuid.uuid4()),
            sender_id=user.id,
            receiver_id=receiver_id,
            status='pending',
            create_time=to_beijing_time(datetime.utcnow())
        )
            
        db.session.add(friend_request)
        db.session.commit()
        return HResult().get_result('success', '好友请求已发送!', friend_request.to_dict())

class CancelFollowRequest(Resource):
    """取消关注"""
    method_decorators = [jwt_required()]

    def post(self):
        data = request.get_json()
        request_id = data.get('request_id')
        user_id = data.get('user_id')
        current_user = get_jwt_identity()

        if not request_id and not user_id:
            return HResult().get_result('error', '参数错误!')

        user = User.query.filter_by(name=current_user).first()

        if request_id:
            friend_request = FriendRequests.query.filter_by(id=request_id)
        else:
            # 发送人是我，状态为pending或accepted
            friend_request = FriendRequests.query.filter_by(
                sender_id=user.id,
                receiver_id=user_id
            ).filter(or_(FriendRequests.status == 'pending', FriendRequests.status == 'accepted')).first()

        if not friend_request or friend_request.sender_id != user.id:
            return HResult().get_result('error', '无效的好友请求!')

        if friend_request.status != 'accepted':
            return HResult().get_result('error', '无效的好友请求!')

        # 删除
        friend_request.delete()
        db.session.commit()

        return HResult().get_result('success', '取关成功!')


class HandleFriendRequest(Resource):
    """互关，相当于同意加好友"""
    method_decorators = [jwt_required()]
    
    def post(self):
        data = request.get_json()
        request_id = data.get('request_id')
        current_user = get_jwt_identity()
        
        if not request_id:
            return HResult().get_result('error', '参数错误!')
            
        user = User.query.filter_by(name=current_user).first()
        friend_request = FriendRequests.query.filter_by(id=request_id).first()
        
        if not friend_request or friend_request.receiver_id != user.id:
            return HResult().get_result('error', '无效的好友请求!')
            
        if friend_request.status != 'pending':
            return HResult().get_result('error', '该请求已经处理过!')
            
        friend_request.status = 'accepted'
        db.session.commit()
        
        return HResult().get_result('success', '处理成功!')

class CancelFriendRequest(Resource):
    """取消互关"""
    method_decorators = [jwt_required()]

    def post(self):
        data = request.get_json()
        request_id = data.get('request_id')
        user_id = data.get('user_id')
        current_user = get_jwt_identity()

        if not request_id and not user_id:
            return HResult().get_result('error', '参数错误!')

        user = User.query.filter_by(name=current_user).first()

        if request_id:
            friend_request = FriendRequests.query.filter_by(id=request_id)
        else:
            # 发送人是我，状态为accepted
            friend_request = FriendRequests.query.filter_by(
                sender_id=user.id,
                receiver_id=user_id,
                status='accepted'
            ).first()

        if not friend_request or friend_request.receiver_id != user.id:
            return HResult().get_result('error', '无效的好友请求!')

        friend_request.satus = 'rejected'
        db.session.commit()
        return HResult().get_result('success', '取消成功!')


class QueryReceivedRequests(Resource):
    """查询关注我的人（粉丝）"""
    method_decorators = [jwt_required()]
    
    def get(self):
        current_user = get_jwt_identity()
        user = User.query.filter_by(name=current_user).first()

        # 这样判断会导致取消互关后不会显示
        requests = FriendRequests.query.filter_by(receiver_id=user.id).filter(
            or_(FriendRequests.status == 'pending', FriendRequests.status == 'accepted')
        ).all()

        return HResult().get_result('success', data=[{
            'id': req.id,
            'sender': req.sender.to_dict(),
            'status': req.status,
            'create_time': req.create_time.strftime('%Y-%m-%d %H:%M:%S')
        } for req in requests])

class QuerySentRequests(Resource):
    """查询我的关注"""
    method_decorators = [jwt_required()]
    
    def get(self):
        current_user = get_jwt_identity()
        user = User.query.filter_by(name=current_user).first()

        # 我关注的
        requests = FriendRequests.query.filter_by(sender_id=user.id).filter(
            or_(FriendRequests.status == 'pending', FriendRequests.status == 'accepted')
        ).all()

        # 我互关的
        follow_each_one = FriendRequests.query.filter(
            FriendRequests.receiver_id == user.id,
            FriendRequests.status == 'accepted'
        ).all()

        result = []

        requests_obj = [
            {
                'id': req.id,
                'receiver': req.receiver.to_dict(),
                'status': req.status,
                'create_time': req.create_time.strftime('%Y-%m-%d %H:%M:%S')
            } for req in requests
        ]

        follow_obj = [
            {
                'id': req.id,
                'sender': req.sender.to_dict(),
                'status': 'accepted',
                'create_time': req.create_time.strftime('%Y-%m-%d %H:%M:%S')
            } for req in follow_each_one
        ]

        result = requests_obj + follow_obj

        return HResult().get_result('success', data=result)

api = Api(bp)
api.add_resource(SendFriendRequest, '/send/', endpoint='send')
api.add_resource(CancelFollowRequest, '/cancel_follow/', endpoint='cancel_follow')
api.add_resource(HandleFriendRequest, '/handle/', endpoint='handle')
api.add_resource(CancelFriendRequest, '/cancel_friend/', endpoint='cancel_friend')
api.add_resource(QueryReceivedRequests, '/followers/', endpoint='followers')
api.add_resource(QuerySentRequests, '/follows/', endpoint='follows')